﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinForm_Mes.Common;
using WinForm_Mes.Common.Models.Warehouse;
using WinForm_Mes.Common.PublicFields;
using static DevExpress.Drawing.Printing.Internal.DXPageSizeInfo;
using static WinForm_Mes.WarehouseManagement.WarehouseForm;

namespace WinForm_Mes.WarehouseManagement
{
    /// <summary>
    /// 仓库管理主窗体，负责仓库数据的分页、查询、新增等操作
    /// </summary>
    public partial class WarehouseForm : DevExpress.XtraEditors.XtraForm
    {
        /// <summary>
        /// 构造函数，初始化窗体和分页控件
        /// </summary>
        public WarehouseForm()
        {
            InitializeComponent();
            bindingNavigator1.BindingSource = bindingSource1;
        }

        /// <summary>
        /// 窗体加载事件，初始化分页下拉框并加载默认数据
        /// </summary>
        private async void WarehouseForm_Load(object sender, EventArgs e)
        {
            toolStripComboBox1.Items.Clear();
            toolStripComboBox1.Items.AddRange(new object[] { 5, 10, 20, 50, 100 });
            if (toolStripComboBox1.Items.Count > 2)
            {
                toolStripComboBox1.SelectedIndex = 2; // 默认选中20
            }
            else if (toolStripComboBox1.Items.Count > 0)
            {
                toolStripComboBox1.SelectedIndex = 0; // 至少选中第一项
            }
            toolStripComboBox1.SelectedIndexChanged += ToolStripComboBox1_SelectedIndexChanged;

            // 初次加载数据
            LoadWarehouseData(20);
        }

        /// <summary>
        /// 分页下拉框选项变更事件，重新加载对应页数的数据
        /// </summary>
        private async void ToolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (int.TryParse(toolStripComboBox1.SelectedItem.ToString(), out int pageSize))
            {
                await LoadWarehouseData(pageSize);
            }
        }

        /// <summary>
        /// 调用后端API获取仓库分页数据
        /// </summary>
        /// <param name="dto">查询参数</param>
        /// <returns>分页数据</returns>
        private async Task<ApiPaging<WarehouseModel>> GetWarehouseListAsync(WarehouseDto dto)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 拼接API地址，参数编码防止特殊字符出错
                    string url = $"http://localhost:5113/api/warehouse/getallwarehouse" +
                                 $"?WarehouseCode={Uri.EscapeDataString(dto.WarehouseCode ?? string.Empty)}" +
                                 $"&WarehouseName={Uri.EscapeDataString(dto.WarehouseName ?? string.Empty)}" +
                                 $"&Index={dto.Index}&Size={dto.Size}";

                    var response = await client.GetAsync(url);
                    if (response.IsSuccessStatusCode)
                    {
                        ApiPaging<WarehouseModel> result = await response.Content.ReadFromJsonAsync<ApiPaging<WarehouseModel>>();
                        bindingSource1.DataSource = result.Items;
                        gridControl1.DataSource = result.Items;
                        toolStripLabel1.Text= $"{result.Total} 条数据";
                        int totalPages = (int)Math.Ceiling((double)result.Total / result.PageSize);
                        bindingNavigatorCountItem.Text = $"第 {result.PageIndex} 页 / 共 {totalPages} 页";
                        return result;
                    }
                    else
                    {
                        MessageBox.Show("接口调用失败：" + response.StatusCode);
                        return new ApiPaging<WarehouseModel> { Items = new List<WarehouseModel>() };
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("接口调用异常：" + ex.Message);
                return new ApiPaging<WarehouseModel> { Items = new List<WarehouseModel>() };
            }
        }

        /// <summary>
        /// 加载仓库数据到表格
        /// </summary>
        /// <param name="pageSize">每页条数</param>
        private async Task LoadWarehouseData(int pageSize)
        {
            var dto = new WarehouseDto
            {
                WarehouseCode = textEdit1.Text,
                WarehouseName = textEdit2.Text,
                Index = PublicFields.currentPage,
                Size = pageSize
            };
            var apiPaging = await GetWarehouseListAsync(dto);
            gridControl1.DataSource = apiPaging.Items;
            gridControl1.RefreshDataSource();
            PublicFields.totalPages = (int)Math.Ceiling((double)apiPaging.Total / apiPaging.PageSize);

            // 更新按钮状态
            UpdateNavigatorButtonStatus();
        }

        /// <summary>
        /// 更新分页按钮的可用状态
        /// </summary>
        private void UpdateNavigatorButtonStatus()
        {
            // 当前页为第一页，上一页和首页按钮不可用
            bindingNavigatorMoveFirstItem.Enabled = PublicFields.currentPage > 1;
            bindingNavigatorMovePreviousItem.Enabled = PublicFields.currentPage > 1;

            // 当前页为最后一页，下一页和末页按钮不可用
            bindingNavigatorMoveNextItem.Enabled = PublicFields.currentPage < PublicFields.totalPages;
            bindingNavigatorMoveLastItem.Enabled = PublicFields.currentPage < PublicFields.totalPages;
        }

        #region 分页按钮
        /// <summary>
        /// 首页按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void bindingNavigatorMoveFirstItem_Click(object sender, EventArgs e)
        {
            PublicFields.currentPage = 1;
            await LoadWarehouseData(Convert.ToInt32(toolStripComboBox1.Text));
        }
        /// <summary>
        /// 上一页按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void bindingNavigatorMovePreviousItem_Click(object sender, EventArgs e)
        {
            if (PublicFields.currentPage > 1)
            {
                PublicFields.currentPage--;
                await LoadWarehouseData(Convert.ToInt32(toolStripComboBox1.Text));
            }
        }
        /// <summary>
        /// 下一页按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void bindingNavigatorMoveNextItem_Click(object sender, EventArgs e)
        {
            if (PublicFields.currentPage < PublicFields.totalPages)
            {
                PublicFields.currentPage++;
                await LoadWarehouseData(Convert.ToInt32(toolStripComboBox1.Text));
            }
        }
        /// <summary>
        /// 尾页按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void bindingNavigatorMoveLastItem_Click(object sender, EventArgs e)
        {
            PublicFields.currentPage = PublicFields.totalPages;
            await LoadWarehouseData(Convert.ToInt32(toolStripComboBox1.Text));
        }
        #endregion

        /// <summary>
        /// 查询按钮点击事件，按条件查询仓库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            var dto = new WarehouseDto
            {
                WarehouseCode = textEdit1.Text,
                WarehouseName = textEdit2.Text,
                Index = PublicFields.currentPage,
                Size = Convert.ToInt32(toolStripComboBox1.Text) // 默认每页20条数据
            };
            GetWarehouseListAsync(dto);
        }

        /// <summary>
        /// 新增仓库按钮点击事件，弹出新增窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton2_Click(object sender, EventArgs e)
        {
            // 1. 请求后端获取新采购单号
            string apiUrl = "http://localhost:5113/api/Warehouse/GetWarehouseCode";
            string newOrderNumber = "";
            try
            {
                HttpResponseMessage response = await PublicFields.client.GetAsync(apiUrl);
                response.EnsureSuccessStatusCode();
                string responseContent = await response.Content.ReadAsStringAsync();
                newOrderNumber = responseContent;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取仓库编码失败: {ex.Message}");
                return;
            }
            WarehouseAddForm warehouseAddForm = new WarehouseAddForm(newOrderNumber);
            warehouseAddForm.WarehouseAdded += RefreshWarehouseList; // 订阅委托
            warehouseAddForm.StartPosition = FormStartPosition.CenterParent;
            warehouseAddForm.ShowDialog(this);
        }

        // 刷新方法
        private void RefreshWarehouseList()
        {
            // 重新加载数据
            LoadWarehouseData(Convert.ToInt32(toolStripComboBox1.Text));
        }

        private void toolStripComboBox1_Click(object sender, EventArgs e)
        {

        }

        private void bindingNavigator1_RefreshItems(object sender, EventArgs e)
        {

        }
    }
}